package com.ctfo.ulcp.exp.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.kotlin.KotlinModule;

import java.text.SimpleDateFormat;
import java.util.Map;

public class JsonCodec {

    private static final ObjectMapper mapper = JsonMapper.builder()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
            .build()
            .registerModules(new JavaTimeModule(), new KotlinModule.Builder().build())
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            );

    private static final JavaType MAP_TYPE = mapper.getTypeFactory().constructParametricType(Map.class, String.class, Object.class);

    public static Map<String, Object> decodeValue(String str) throws JsonProcessingException {
        return mapper.readValue(str, MAP_TYPE);
    }


    public static <T> T decodeValue(String str, TypeReference<T> type) throws JsonProcessingException {
        return mapper.readValue(str, type);
    }

    public static <T> T decodeValue(String str, Class<T> clz) throws JsonProcessingException {
        return mapper.readValue(str, clz);
    }

    public static String encode(Object obj) throws JsonProcessingException {
        return mapper.writeValueAsString(obj);
    }



}
